// pages/index/remote/remote.js
const app = getApp()
const bluetoothUtils = require("../../../utils/bluetoothUtils")
const util = require('../../../utils/util')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        tabIndex: 0,
        timeIndex: 0,
        massage_duration: '关闭',
        dialogShow: false,
        msg: {
            content: '',
            title: '',
            btntext: '',
            tips: false
        },
        anmolevel: 0,
        anmolevel2: 0,
        bedToHeaderInId: "",
        bedToHeaderOutId: "",
        bedToFooterInId: "",
        bedToFooterOutId: "",
        bedAToHeaderInId: "",
        bedAToHeaderOutId: "",
        bedBToHeaderInId: "",
        bedBToHeaderOutId: "",
        deviceID: null, //设备ID
        bluetoothInfo: null, //记录蓝牙的基本信息
        handleFlag: false,
        handletext: '一键入眠'
    },
    changeTab: function (e) {
        let index = e.currentTarget.dataset.index
        this.setData({
            tabIndex: index
        })
    },
    // 头部
    startbedToHeaderIn() {
        let _this = this
        _this.data.bedToHeaderInId = setInterval(function () {
            _this.bedToHeaderIn()
        }, 150);
    },
    enDbedToHeaderIn() {
        let _this = this
        console.log('清除头部伸出定时器')
        clearInterval(_this.data.bedToHeaderInId)
    },
    startbedToHeaderOut() {
        let _this = this
        _this.data.bedToHeaderOutId = setInterval(function () {
            _this.bedToHeaderOut()
        }, 150);
    },
    enDbedToHeaderOut() {
        let _this = this
        console.log('清除头部缩进定时器')
        clearInterval(_this.data.bedToHeaderOutId)
    },
    // 脚部
    startbedToFooterIn() {
        let _this = this
        _this.data.bedToFooterInId = setInterval(function () {
            _this.bedToFooterIn()
        }, 150);
    },
    enDbedToFooterIn() {
        let _this = this
        console.log('清除脚部伸出定时器')
        clearInterval(_this.data.bedToFooterInId)
    },
    startbedToFooterOut() {
        let _this = this
        _this.data.bedToFooterOutId = setInterval(function () {
            _this.bedToFooterOut()
        }, 150);
    },
    enDbedToFooterOut() {
        let _this = this
        console.log('清除脚部缩进定时器')
        clearInterval(_this.data.bedToFooterOutId)
    },
    // 头部驱动器伸出
    bedToHeaderIn: async function () {
        let _this = this;
        // let sendmessageRes = await this.sendMsg("E6FE1601000000004");
        let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040101000000F9F355");
        util.insertRemoteKey(app.globalData.deviceId, 'headup', "AA03000A00040101000000F9F355")
        this.initData()
        this.setData({
            massage_duration: '关闭'
        })
        console.log("头部驱动器伸出:", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
    },
    // 头部驱动器缩进
    bedToHeaderOut: async function () {
        let _this = this;
        // let sendmessageRes = await this.sendMsg("E6FE16020000000003");
        let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040102000000F8F355");
        util.insertRemoteKey(app.globalData.deviceId, 'headdown', "AA03000A00040102000000F8F355")
        this.initData()
        this.setData({
            massage_duration: '关闭'
        })
        console.log("头部驱动器缩进", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
    },
    // 脚部驱动器伸出
    bedToFooterIn: async function () {
        let _this = this;
        // let sendmessageRes = await this.sendMsg("E6FE16040000000001");
        let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040104000000F6F355");
        util.insertRemoteKey(app.globalData.deviceId, 'footup', "AA03000A00040104000000F6F355")
        console.log("脚部驱动器伸出", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
    },
    // 脚部驱动器缩进
    bedToFooterOut: async function () {
        let _this = this;
        // let sendmessageRes = await this.sendMsg("E6FE160800000000FD");
        let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040108000000F2F355");
        util.insertRemoteKey(app.globalData.deviceId, 'footdown', "AA03000A00040108000000F2F355")
        this.initData()
        this.setData({
            massage_duration: '关闭'
        })
        console.log("脚部驱动器缩进", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
    },
    // 零压力
    bedToZero: async function () {
        let _this = this;
        // let sendmessageRes = await this.sendMsg("E6FE160010000000F5");
        let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040100100000EAF355");
        util.insertRemoteKey(app.globalData.deviceId, 'zeroG', "AA03000A00040100100000EAF355")
        this.initData()
        this.setData({
            massage_duration: '关闭'
        })
        console.log("零压力", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
    },
    // 一键放平
    bedToFlat: async function () {
        let _this = this;
        // let sendmessageRes = await this.sendMsg("E6FE160000000800FD");
        let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040100000008F2F355");
        util.insertRemoteKey(app.globalData.deviceId, 'Flat', "AA03000A00040100000008F2F355")
        this.initData()
        this.setData({
            massage_duration: '关闭'
        })
        console.log("一键放平:", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
        setTimeout(() => {
            _this.stuatsSearch()
        }, 1000);
    },
    // TV模式
    bedToTV: async function () {
        let _this = this;
        // let sendmessageRes = await this.sendMsg("E6FE160040000000c5");
        let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040100400000BAF355");
        util.insertRemoteKey(app.globalData.deviceId, 'TV', "AA03000A00040100400000BAF355")
        this.initData()
        this.setData({
            massage_duration: '关闭'
        })
        console.log("TV模式:", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
    },
    // 阅读模式
    bedToRead: async function () {
        let _this = this;
        // let sendmessageRes = await this.sendMsg("E6FE160020000000e5");
        let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040100200000DAF355");
        util.insertRemoteKey(app.globalData.deviceId, 'Read', "AA03000A00040100200000DAF355")
        this.initData()
        this.setData({
            massage_duration: '关闭'
        })
        console.log("阅读模式:", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
    },
    // 头部按摩
    bedToHeadAnmo: async function () {
        this.headMsg()
        let sendmessageRes = await bluetoothUtils.sendMsg("00B0");
    },
    headMsg: async function () {
        let _this = this;
        // let sendmessageRes = await this.sendMsg("E6FE160008000000fd");
        let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040100080000F2F355");
        util.insertRemoteKey(app.globalData.deviceId, 'headAnmo', "AA03000A00040100080000F2F355")
        this.initData()
        if (this.data.anmolevel == 0) {
            this.setData({
                massage_duration: '10分钟',
                anmolevel: 1
            })
        } else if (this.data.anmolevel == 1) {
            this.setData({
                massage_duration: '10分钟',
                anmolevel: 2
            })
        } else if (this.data.anmolevel == 2) {
            this.setData({
                massage_duration: '10分钟',
                anmolevel: 3
            })
        } else if (this.data.anmolevel == 3) {
            if (this.data.anmolevel2 == 0) {
                this.setData({
                    massage_duration: '关闭',
                    anmolevel: 0
                })
            } else {
                this.setData({
                    massage_duration: '10分钟',
                    anmolevel: 0
                })
            }
        }

        console.log("头部按摩:", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
        setTimeout(() => {
            _this.stuatsSearch()
        }, 1000);
    },
    // 脚部按摩
    bedToFootAnmo: async function () {
        this.footMsg()
        let sendmessageRes = await bluetoothUtils.sendMsg("00B0");

    },
    footMsg: async function () {
        let _this = this;
        // let sendmessageRes = await this.sendMsg("E6FE16000400000001");
        let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040100040000F6F355");
        util.insertRemoteKey(app.globalData.deviceId, 'footAnmo', "AA03000A00040100040000F6F355")
        this.initData()
        if (this.data.anmolevel2 == 0) {
            this.setData({
                massage_duration: '10分钟',
                anmolevel2: 1
            })
        } else if (this.data.anmolevel2 == 1) {
            this.setData({
                massage_duration: '10分钟',
                anmolevel2: 2
            })
        } else if (this.data.anmolevel2 == 2) {
            this.setData({
                massage_duration: '10分钟',
                anmolevel2: 3
            })
        } else if (this.data.anmolevel2 == 3) {
            if (this.data.anmolevel == 0) {
                this.setData({
                    massage_duration: '关闭',
                    anmolevel2: 0
                })
            } else {
                this.setData({
                    massage_duration: '10分钟',
                    anmolevel2: 0
                })
            }
        }
        console.log("脚部按摩:", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
        setTimeout(() => {
            _this.stuatsSearch()
        }, 1000);
    },
    // 按摩时长
    bedToAnmoTime: async function () {
        this.AnmoTimeMsg()
        let sendmessageRes = await bluetoothUtils.sendMsg("00B0");
        if (this.data.massage_duration == '关闭') {
            this.setData({
                massage_duration: '10分钟'
            })
        } else if (this.data.massage_duration == '10分钟') {
            this.setData({
                massage_duration: '20分钟'
            })
        } else if (this.data.massage_duration == '20分钟') {
            this.setData({
                massage_duration: '30分钟'
            })
        } else {
            this.setData({
                massage_duration: '关闭'
            })
        }

    },
    AnmoTimeMsg: async function () {
        let _this = this;
        // let sendmessageRes = await this.sendMsg("E6FE16000200000003");
        let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040100020000F8F355");
        util.insertRemoteKey(app.globalData.deviceId, 'AnmoTime', "AA03000A00040100020000F8F355")
        this.initData()
        console.log("按摩时长:", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
        setTimeout(() => {
            _this.stuatsSearch()
        }, 1000);
    },
    // 停止按摩
    bedToStopAnmo: async function () {
        let _this = this;
        // let sendmessageRes = await this.sendMsg("E6FE16000000020003");
        let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040100000002F8F355");
        util.insertRemoteKey(app.globalData.deviceId, 'stopAnmo', "AA03000A00040100000002F8F355")
        this.initData()
        console.log("停止按摩:", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
        this.setData({
            massage_duration: '关闭'
        })
        // setTimeout(() => {
        //     _this.stuatsSearch()
        // }, 1000);

    },
    // 舒缓解压
    bedToSHJY: async function () {
        let _this = this;
        this.setData({
            massage_duration: '关闭'
        })
        let sendmessageRes = await bluetoothUtils.sendMsg("AA0B001000100A040404040000EE0A0000DDE555");
        util.insertRemoteKey(app.globalData.deviceId, 'SHJY', "AA0B001000100A040404040000EE0A0000DDE555")
        this.initData()
        console.log("舒缓解压:", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
    },
    // 放松助眠
    bedToFSZM: async function () {
        let _this = this;
        this.setData({
            massage_duration: '关闭'
        })
        let sendmessageRes = await bluetoothUtils.sendMsg("AA0B001000100A020202020000EE090000E6E555");
        util.insertRemoteKey(app.globalData.deviceId, 'FSZM', "AA0B001000100A020202020000EE090000E6E555")
        this.initData()
        console.log("放松助眠:", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
    },
    // 肩颈放松
    bedToJJFS: async function () {
        let _this = this;
        this.setData({
            massage_duration: '关闭'
        })
        let sendmessageRes = await bluetoothUtils.sendMsg("AA0B001000100A040404040000EE140000D3E555");
        util.insertRemoteKey(app.globalData.deviceId, 'JJFS', "AA0B001000100A040404040000EE140000D3E555")
        this.initData()
        console.log("肩颈放松:", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
        }
    },
    // 腰部放松
    bedToYBFS: async function () {
        let _this = this;
        this.setData({
            massage_duration: '关闭'
        })
        let sendmessageRes = await bluetoothUtils.sendMsg("AA0B001000100A030303030000EE0E0000DDE555");
        util.insertRemoteKey(app.globalData.deviceId, 'YBFS', "AA0B001000100A030303030000EE0E0000DDE555")
        this.initData()
        console.log("腰部放松:", sendmessageRes);
        if (!sendmessageRes) {
            this.closeBleCon("蓝牙连接中断，请重试");
            s
        }
    },
    //舒缓解压弹窗
    relieveStress: function () {
        this.setData({
            dialogShow: true,
            msg: {
                content: '易焦虑人群，上班族压力山大,只想躺平?\n舒缓解压模式,10分钟减少焦虑和压力。当床按摩时的振动频率达到38-44Hz时,可以达到舒缓解压作用。',
                title: '舒缓解压',
                btntext: '立即开启',
                tips: 2
            },
        })
    },
    //放松助眠弹窗
    relaxation: function () {
        this.setData({
            dialogShow: true,
            msg: {
                content: '失眠星球人,翻来覆去睡不着?\n放松助眠模式,低赫兹唤起睡意,缓解失眠。\n当床按摩时的振动频率达到40Hz时,有助于帮助您更好得入睡。',
                title: '放松助眠',
                btntext: '立即开启',
                tips: 2
            },
        })
    },
    //肩颈放松弹窗
    shoulderNeckRelax: function () {
        this.setData({
            dialogShow: true,
            msg: {
                content: '伏案久坐、低头刷屏、颈椎不堪重负?\n一键点击肩颈放松,释放肩颈压力。\n当床按摩时的振动频率达到68Hz时,可以有效放松您的肩部和颈部。',
                title: '肩颈放松',
                btntext: '立即开启',
                tips: 2
            },
        })
    },
    //腰部放松弹窗
    waistRelax: function () {
        this.setData({
            dialogShow: true,
            msg: {
                content: '腰部不适,酸胀疼痛,怎么睡都不对?\n立即开启腰部放松,促进血液循环,减轻腰痛。\n当床按摩时的振动频率达到52Hz时,可以有效放松您的腰部。',
                title: '腰部放松',
                btntext: '立即开启',
                tips: 2
            },
        })
    },
    dialogHandle2: function (e) {
        this.setData({
            dialogShow: e.detail.params
        })
        if (e.detail.text == 'confirm') {
            switch (this.data.msg.title) {
                case '舒缓解压':
                    this.bedToSHJY()
                    break;
                case "放松助眠":
                    this.bedToFSZM()
                    break;
                case "肩颈放松":
                    this.bedToJJFS()
                    break;
                case "腰部放松":
                    this.bedToYBFS()
                    break;
            }
        }
    },
    stuatsSearch: async function () {
        let _this = this
        let flag
        // wx.onBLECharacteristicValueChange(function (characteristic) {
        // 	console.log(_this.ab2hex(characteristic.value))
        // 	// flag = _this.ab2hex(characteristic.value).slice(27, 28)
        // 	// if (flag == 1) {
        // 	// 	_this.setData({
        // 	// 		musicMassageFlag: true
        // 	// 	})
        // 	// } else {
        // 	// 	_this.setData({
        // 	// 		musicMassageFlag: false
        // 	// 	})
        // 	// }
        // 	let t1 = _this.ab2hex(characteristic.value).slice(7, 8)
        // 	let t2 = _this.ab2hex(characteristic.value).slice(8, 9)
        // 	let t3 = _this.ab2hex(characteristic.value).slice(9, 10)
        // 	t1 = _this.hex_change(t1)
        // 	t2 = _this.hex_change(t2)
        // 	t3 = _this.hex_change(t3)
        // 	if (t1 * 16 * 16 + t2 * 16 + t1 == 0) {
        // 		_this.setData({
        // 			massage_duration: '关闭'
        // 		})
        // 	} else if (t1 * 16 * 16 + t2 * 16 + t1 <= 600) {
        // 		_this.setData({
        // 			massage_duration: '10分钟'
        // 		})
        // 	} else if (t1 * 16 * 16 + t2 * 16 + t1 <= 1200) {
        // 		_this.setData({
        // 			massage_duration: '20分钟'
        // 		})
        // 	} else {
        // 		_this.setData({
        // 			massage_duration: '30分钟'
        // 		})
        // 	}
        // })
        // let sendmessageRes = await bluetoothUtils.sendMsg("00B0");
    },
    ab2hex(buffer) {
        let hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function (bit) {
                return ('00' + bit.toString(16)).slice(-2)
            }
        )
        return hexArr.join('');
    },
    //16进制字符串转ArrayBuffer
    hexStringToArrayBuffer(str) {
        if (!str) {
            return new ArrayBuffer(0);
        }
        var buffer = new ArrayBuffer(str.length);
        let dataView = new DataView(buffer)
        let ind = 0;
        for (let i = 0, len = str.length; i < len; i += 2) {
            let code = parseInt(str.substr(i, 2), 16)
            dataView.setUint8(ind, code)
            ind++
        }
        return buffer;
    },
    sendMsgAgain: async function (msg) {
        // console.log("success sendMsgAgain:", res);
        let sendResult = await bluetoothUtils.sendMsg(msg);
        if (sendResult) {
            resolve(sendResult);
        } else {
            resolve();
        }
    },
    hex_change: function (v) {
        var res;
        switch (v) {
            case "a":
                res = 10;
                break;
            case "b":
                res = 11;
                break;
            case "c":
                res = 12;
                break;
            case "d":
                res = 13;
                break;
            case "e":
                res = 14;
                break;
            case "f":
                res = 15;
                break;
            case "1":
            case "2":
            case "3":
            case "4":
            case "5":
            case "6":
            case "7":
            case "8":
            case "9":
                res = Number(v);
                break;
            default:
                res = 0;
                break;
        }
        return res;
    },
    initData() {
        app.globalData.BRDATA = null
        app.globalData.HRDATA = null
        app.globalData.setBR = null
        app.globalData.setHR = null
        wx.setStorageSync('smartRelax', null)
        wx.setStorageSync('oneManSleep', null)
        wx.setStorageSync('remote', true)
        app.globalData.playmusic = wx.getBackgroundAudioManager()
        app.globalData.playmusic.stop()
        this.setData({
            handleFlag: false
        })
    },
    close() {
        this.setData({
            handleFlag: false
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let temp1 = wx.getStorageSync('oneManSleep')
        if (temp1 != null && temp1 != undefined) {
            this.setData({
                handleFlag: true,
                handletext: '一键入眠'
            })
        }
        let temp2 = wx.getStorageSync('smartRelax')
        if (temp2 != null && temp2 != undefined) {
            this.setData({
                handleFlag: true,
                handletext: '智能放松'
            })
        }
        console.log('StorageSync====>', temp1, temp2)
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})